﻿using ApiGateway.Config;
using ApiGateway.Interface;
using RpcHelper;
using RpcHelper.Config;
using RpcModular;

namespace ApiGateway.PlugIn
{
    /// <summary>
    /// 接口屏蔽插件
    /// </summary>
    internal class ShieIdPlugIn : BasicPlugIn, IShieIdPlugIn
    {
        private readonly IResourceShieldService _Service;
        private ApiShieldConfig _Config;
        public ShieIdPlugIn(IResourceShieldService service,IConfigCollect configCollect) : base("ApiShieId")
        {
            this._Service = service;
            ApiShieldConfig config = configCollect.GetValue("gateway:shieId", new ApiShieldConfig());
            configCollect.RefreshEvent+=this._Refresh;
            this._Init(config);
        }
        public override bool IsEnable => this._Config.IsEnable;
        private void _Init(ApiShieldConfig config)
        {
            if (config.IsEnable && config.IsLocal && config.ShieIdPath==null)
            {
                config.ShieIdPath = new string[0];
            }
            this._Config = config;
            if (!config.IsEnable)
            {
                this._Service.Dispose();
            }
            else
            {
                this._Service.Init();
            }
        }
        private void _Refresh(IConfigCollect server, string name)
        {
            if (name == "gateway:shieId" || name.StartsWith("gateway:shieId:"))
            {
                ApiShieldConfig  config= server.GetValue("gateway:shieId", new ApiShieldConfig());
                this._Init(config);
                base._ChangeEvent();
            }
        }

        protected override void _Dispose()
        {
            if (this._Config.IsEnable)
            {
                this._Service.Dispose();
            }
        }

        public bool CheckIsShieId(string path)
        {
            if (_Config.IsLocal)
            {
                return this._Config.ShieIdPath.IsExists(path);
            }
            return this._Service.CheckIsShieId(path);
        }
    }
}
